import React, { useEffect, useState } from 'react';
import { message, Modal, Tree } from 'antd';
import { connect } from 'umi';
import { ConnectState } from '@/models/connect';
import { getDashboardList, updateRoleDashboard } from '@/services/information';
import { PieChartOutlined } from '@ant-design/icons';
import './style.less'
const { DirectoryTree } = Tree;
const EditJurisdiction: React.FC<any> = (props:any) => {
  const{onCancel,visible,projectId,roleId}=props
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>([]);
  const [treeData, setTreeData] = useState<any>([]);
  const [autoExpandParent, setAutoExpandParent] = useState<boolean>(true);
//转换树型结构
  function toTree(data:any[]=[], pid:any) {
    let result = [], temp;
    for (let i = 0; i < data.length; i++) {
      let item = data[i];
      if (item['parentId'] === pid) {
        let isLeaf=item.type==0?false:true
        const obj = {title: item.name,key: item.id,isLeaf};
        if(isLeaf){
          obj['icon']=<PieChartOutlined/>
        }
        temp = toTree(data, item.id);
        if (temp.length > 0) {
          obj['children'] = temp;
          result.push(obj);
        }
        if(isLeaf){
          result.push(obj);
        }
      }
    }
    return result;
  }

  useEffect(()=>{
    getDashboardList({projectId,roleId}).then(resp=>{
      const{dashboards=[],selected=[]}=resp.payload
      const data= toTree(dashboards,0,)
      setTreeData(data)
      setCheckedKeys(selected)
      setExpandedKeys(selected);
    })
  },[])
  const onExpand = (expandedKeysValue: React.Key[]) => {
    setExpandedKeys(expandedKeysValue)
    setAutoExpandParent(false);
  };

  const onCheck = (checkedKeysValue: React.Key[],info: any) => {
    let checkedNodes = info.checkedNodes.filter((item:any)=>item.isLeaf).map((item:any)=>item.key)
    setCheckedKeys(checkedNodes);
  };

  function save() {
    let dashboardIds=checkedKeys
    updateRoleDashboard({dashboardIds,roleId}).then(resp=>{
      const{header}=resp
      if(header&&header.code===200){
        message.success('操作成功')
        onCancel()
      }else {
        message.error('操作失败')
      }
    })
  }

  return (
    <Modal
      width={500}
      bodyStyle={{ padding: '32px 40px 48px' }}
      title="权限编辑"
      visible={visible}
      onOk={save}
      onCancel={onCancel}
    >
      <DirectoryTree
        checkable
        onExpand={onExpand}
        expandedKeys={expandedKeys}
        autoExpandParent={autoExpandParent}
        onCheck={onCheck}
        checkedKeys={checkedKeys}
        treeData={treeData}
      />
    </Modal>
  );
};

export default connect(({  }: ConnectState) => ({
}))(EditJurisdiction);
